//
//  LoginViewController.m
//  MZJ
//
//  Created by XDD on 16/6/2.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "LoginViewController.h"
#import "TabBarViewController.h"
#import "LoginView.h"

@interface LoginViewController ()<ModelDelegate,UITextFieldDelegate> {
    NSInteger startTime_;
}

@property (nonatomic, strong) LoginView *loginView;
@property (nonatomic, strong) NetWorkingSModel *model;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) ModelViewController *modelViewController;

@end

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.loginView.hidden = NO;
    if (!_model) {
        _model = [[NetWorkingSModel alloc] init];
        
        self.topBar.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
        self.titleLabel.text = @"手机登陆";
        self.titleLabel.textColor = [UIColor blackColor];
        
        UIButton *skipButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [skipButton setTitle:@"跳过" forState:UIControlStateNormal];
        [skipButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        skipButton.titleLabel.font = [UIFont systemFontOfSize:16];
        skipButton.frame = CGRectMake(kWidth - 45, 23, 40, 25);
        [skipButton addTarget:self action:@selector(skipButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [self.topBar addSubview:skipButton];
    }
    if (!_modelViewController) {
        _modelViewController = [[ModelViewController alloc] init];
    }
}

- (void)skipButtonAction {
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

- (LoginView *)loginView {
    if (!_loginView) {
        _loginView = [[LoginView alloc]initWithFrame:self.view.bounds];
        //    layerView.backgroundColor = [UIColor redColor];
        [self.view addSubview:_loginView];

        __weak typeof (self)weakSelf = self;
        [_loginView setDidgetcodeButtonBlock:^{
            //数据请求接口的调用
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            
            if (weakSelf.loginView.phoneNum_textField.text.length != 11)
            {
                [weakSelf waringAction:@"请输入11位有效手机号!"];
                
            }else{
                /**
                 * 移动号段正则表达式
                 */
                NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
                /**
                 * 联通号段正则表达式
                 */
                NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
                /**
                 * 电信号段正则表达式
                 */
                NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
                
                NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
                BOOL isMatch1 = [pred1 evaluateWithObject:weakSelf.loginView.phoneNum_textField.text];
                NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
                BOOL isMatch2 = [pred2 evaluateWithObject:weakSelf.loginView.phoneNum_textField.text];
                NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
                BOOL isMatch3 = [pred3 evaluateWithObject:weakSelf.loginView.phoneNum_textField.text];
                
                if (isMatch1 || isMatch2 || isMatch3) {

                    startTime_ = 60;
                    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(action_onTimer) userInfo:nil repeats:YES];
                    weakSelf.loginView.getCodeBtn.enabled = NO;
                    [dic setObject:weakSelf.loginView.phoneNum_textField.text forKey:@"umobile"];   //调接口时需要的参数
                    
                    [weakSelf.model setBlockWithReturnBlock:^(id returnValue) {
                        NSLog(@"%@",returnValue);
                    
                    } WithErrorBlock:^(id errorCode) {
                        [weakSelf waringAction:errorCode[@"result"]];
                    }];
                    [weakSelf.model userGetCode:dic];

                }else{
                    [weakSelf waringAction:@"请输入正确的手机号!"];
                }
            }

            
//            if (weakSelf.loginView.phoneNum_textField.text.length != 11) {
//                //弹框
//                [weakSelf waringAction:@"请输入正确的手机号!"];
//            }else {
//                startTime_ = 60;
//                _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(action_onTimer) userInfo:nil repeats:YES];
//                weakSelf.loginView.getCodeBtn.enabled = NO;
//                [dic setObject:weakSelf.loginView.phoneNum_textField.text forKey:@"umobile"];   //调接口时需要的参数
//                
//                [weakSelf.model setBlockWithReturnBlock:^(id returnValue) {
//                    NSLog(@"%@",returnValue);
//                    
//                } WithErrorBlock:^(id errorCode) {
//                    [weakSelf waringAction:errorCode[@"result"]];
//                }];
//                [weakSelf.model userGetCode:dic];
//            }
            
            
            
            
        }];
        
        [_loginView setDidloginbtnButtonBlock:^{
//            if (weakSelf.loginView.phoneNum_textField.text.length != 11 || weakSelf.loginView.codeNum_textField.text.length != 4) {
//                [weakSelf waringAction:@"请输入正确的手机号或验证码!"];
//            }
            if (weakSelf.loginView.phoneNum_textField.text.length != 11) {
                [weakSelf waringAction:@"请输入正确的手机号或验证码!"];
            }
            else {
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                [dic setObject:weakSelf.loginView.phoneNum_textField.text forKey:@"umobile"];   //调接口时需要的参数
                [dic setObject:weakSelf.loginView.codeNum_textField.text forKey:@"code"];   //调接口时需要的参数
                [weakSelf.model setBlockWithReturnBlock:^(id returnValue) {
                    
                    NSLog(@"%@",returnValue);
                    
                    NSUserDefaults *users = [NSUserDefaults standardUserDefaults];
                        
                    [users setObject:returnValue[@"result"][@"token"] forKey:@"user_token"];
                    
                    [DataModel object].statu_Str = returnValue[@"statu"];
                    [DataModel object].userDetail = returnValue[@"result"][@"user"];

                    [weakSelf person_data_httprequest];
                    [weakSelf.navigationController popViewControllerAnimated:YES];

                } WithErrorBlock:^(id errorCode) {
//
                    if ([[NSString stringWithFormat:@"%@",errorCode] isEqualToString:@"网络连接失败！"]) {
                        [weakSelf waringAction:errorCode];
                    } else {
                        [weakSelf waringAction:errorCode[@"result"]];
                    }
                }];
                [weakSelf.model userGetLogin:dic];
            }
        }];
        
//        [_loginView setDidQQbtnButtonBlock:^{
//            UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
//            
//            snsPlatform.loginClickHandler(weakSelf,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
//                
//                //          获取微博用户名、uid、token等
//                NSLog(@"%u",response.responseCode);
//                if (response.responseCode == UMSResponseCodeSuccess) {
//                    
//                    //            NSDictionary *dict = [UMSocialAccountManager socialAccountDictionary];
//                    UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:snsPlatform.platformName];
//                    NSLog(@"\nusername = %@,\n usid = %@,\n token = %@ iconUrl = %@,\n unionId = %@,\n thirdPlatformUserProfile = %@,\n thirdPlatformResponse = %@ \n, message = %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL, snsAccount.unionId, response.thirdPlatformUserProfile, response.thirdPlatformResponse, response.message);
//                }});
//        }];
        
//        [_loginView setDidWXbtnButtonBlock:^{
//            UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
//            
//            snsPlatform.loginClickHandler(weakSelf,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
//                
//                if (response.responseCode == UMSResponseCodeSuccess) {
//                    
//                    //            NSDictionary *dict = [UMSocialAccountManager socialAccountDictionary];
//                    UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:snsPlatform.platformName];
//                    NSLog(@"\nusername = %@,\n usid = %@,\n token = %@ iconUrl = %@,\n unionId = %@,\n thirdPlatformUserProfile = %@,\n thirdPlatformResponse = %@ \n, message = %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL, snsAccount.unionId, response.thirdPlatformUserProfile, response.thirdPlatformResponse, response.message);
//                }
//                
//            });
//        }];
    }
    return _loginView;
}

- (void)person_data_httprequest {
    if (!_model) {
        _model = [[NetWorkingSModel alloc] init];
    }
    __weak typeof (self)weakSelf = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *token = [user objectForKey:@"user_token"];
    if (token.length != 0) {
        
        [dic setObject:token forKey:@"token"];
    }
    [_model setBlockWithReturnBlock:^(id returnValue) {
        
        [weakSelf.modelViewController userInfo_data_save:@"useDetail.txt" responseObject:returnValue[@"result"]];
        [DataModel object].userDetail = returnValue[@"result"];
        //        NSLog(@"个人信息下载 = %@",returnValue);
    } WithErrorBlock:^(id errorCode) {
        NSLog(@"%@",errorCode);
        if ([[NSString stringWithFormat:@"%@",errorCode] isEqualToString:@"网络连接失败！"]) {
            [DataModel object].statu_Str = @"1";
        } else {
            [DataModel object].statu_Str = errorCode[@"statu"];
        }
        
    }];
    [weakSelf.model userGetUserinfo:dic];
}

- (void)action_onTimer {
    
    [_loginView.getCodeBtn setTitle:[NSString stringWithFormat:@"%lds",(long)startTime_] forState:UIControlStateNormal];
    
    if (startTime_ > 0) {
        startTime_ -= 1;
    }
    if (startTime_ == 0) {
//        _timer = nil;
//        [_timer invalidate];
        [_timer setFireDate:[NSDate distantFuture]];
        [_loginView.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _loginView.getCodeBtn.enabled = YES;
    }
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
    //UIStatusBarStyleDefault = 0 黑色文字，浅色背景时使用
    //UIStatusBarStyleLightContent = 1 白色文字，深色背景时使用
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
